import { createStore, Commit } from 'vuex'
import { axios, AxiosRequestConfig } from '../utils/http'
import { StorageHandler, storageType } from '../utils/storage'

const storageHandler = new StorageHandler()

const asyncAndCommit = async (url:string, mutationName:string, commit: Commit,
  config: AxiosRequestConfig = { method: 'get' }, extraData?: any) => {
    const { data } = await axios(url,config)
    if ( extraData) {
      commit(mutationName, { data, extraData })
    } else {
      commit(mutationName, data)
    }

}
 
const store = createStore({
  state: {
    user: { isLogin: false },
    loading: false,
    token: storageHandler.getItem(storageType, 'token') || '',
    columns: { data: {} , currentPage: 0, total: '' },
    posts: { data: {}, loadedColumns: {}},
    error: { status: false }
  },
  mutations: {
    setLoading (state, status) {
      state.loading = status
    },
    login (state, rawData) {
      const { token } = rawData.data
      state.token = token
      storageHandler.setItem(storageType, 'token',token)
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
    }
  },
  actions: {
    login ({ commit },payload) {
      return asyncAndCommit('/api/user/login','login',commit,{ method: 'post',data: payload})  
    },
    register( { commit },payload) {
      return asyncAndCommit('/api/users','register',commit,{ method: 'post',data: payload })
    }
  },
  modules: {
  }
})

export default store
